import router from '@/router'
import store from '@/store'

router.beforeEach(async(to, from, next) => {
  const url = to.path
  const token = store.getters.token
  const whiteList = ['/login', '/404', '/test']
  if (token && url === '/login') {
    next('/')
  }
  if (token && url !== '/login') {
    if (!store.getters.name) {
      await store.dispatch('user/getUserInfo')
      const res = await store.dispatch('permission/filterRoutes', store.getters.menus)
      // 追加路由访问(菜单还没恢复, 另外刷新也会404, 后面在处理)
      router.addRoutes([
        ...res,
        { path: '*', redirect: '/404', hidden: true }
      ])
      next(to.path)
      return
    }
    next()
  }
  if (!token && whiteList.includes(url)) {
    next()
  }
  if (!token && !whiteList.includes(url)) {
    next('/login')
  }
})
